<template>
  <div class="main">
    <div class="filter">
      <el-input placeholder="请输入客户名" type="small" v-model="form.khname" clearable></el-input>
      <el-row>
        <el-col :span="16">
          <el-date-picker
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="开始时间">
          </el-date-picker>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" class="el-icon-search search-btn" @click="getThatDayData">当天所有</el-button>
        </el-col>
        <el-col :span="16">
          <el-date-picker
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="结束时间">
          </el-date-picker>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" class="el-icon-search search-btn" @click="searchBill">查 询</el-button>
        </el-col>
        <el-col :span="24">
          <el-button size="mini" style="width: 100%;" @click="getQuest">有问题单</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="sum">共{{result.length}}张单，总金额￥{{totalJe}}<br/>总欠款￥{{totalQk}}</div>
    <div class="result-dj">
      <div class="box"
           :class="{active: activeIndex === item.dh}"
           :id="'list'+ item.dh"
           v-for="(item,index) in result"
           @click="clickItem(item.dh)"
      >
        <div class="custName">
          {{ item.khname }}
          <div>
            <span class="je" :class="{qk: item.fkfs === '欠款', jj: item.fkfs === '即结'}">￥{{ item.je }}</span>
          </div>
        </div>
        <div class="hide-content">
          <div class="content-item">单号：{{ item.dh }}</div>
          <div class="content-item">日期：{{ item.rq }}</div>
        </div>
      </div>
    </div>
    <div class="dj-detail" ref="djDetail" :class="collapse ? 'collapse' : ''">
      <div class="dj-title">
        <template v-if="curCust">
          <div>{{ curCust.khname }}</div>
          <div class="total-flex">
            <div class="total" :class="{qk: curCust.fkfs === '欠款', jj: curCust.fkfs === '即结'}">￥{{ curCust.je }}</div>
            <i class="el-icon-arrow-down" @click="collapse = !collapse"></i>
          </div>
        </template>
      </div>
      <div class="dj-list">
        <div class="dj-list-item" v-for="item in result_detail[activeIndex]">
          <div class="spname" @click="checkKc(item.spbh)">{{ item.spname }}</div>
          <div class="sl" v-if="item.prnjs.indexOf('0.00') === 0">{{ item.prnxs }}</div>
          <div class="sl" v-else>{{ item.prnjs }}</div>
          <div class="xj">小计: ￥{{ (item.sl * item.jg).toFixed(2) }}</div>
          <div class="dj">单价: ￥{{ item.jg.toFixed(2) }}</div>
          <div class="jj">进价: ￥{{ item.jj.toFixed(2) }}</div>
          <div class="ml">毛利: <span :style="{color: item.jg > item.jj ? '#67c23a' : '#dd6161'}"
          >￥{{ ((item.jg - item.jj) * item.sl).toFixed(2) }}</span>
          </div>
        </div>
      </div>
      <el-dialog :visible="goodStorageDialog" title="库存信息" :before-close="handleClose" width="80%" append-to-body>
        <div v-if="kcInf">
          <h2>{{kcInf.spname}}库存信息</h2>
          <div class="view-line">
            <div class="title">门市库存</div>
            <div class="value">{{ kcInf.mskc + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">门市可用</div>
            <div class="value">{{ kcInf.msky + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">仓库库存</div>
            <div class="value">{{ kcInf.ckkc + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">仓库可用</div>
            <div class="value">{{ kcInf.ckky + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">大昌库存</div>
            <div class="value">{{ kcInf.dckc + kcInf.dw2 }}</div>
          </div>
          <div class="view-line">
            <div class="title">远洋库存</div>
            <div class="value">{{ kcInf.yykc + kcInf.dw2 }}</div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  queryJH,
  getRecentZD,
  getJHdetail,
  getThatDayJH,
  hasReadZd,
  hasQuestZd,
  getQuestZD,
  queryGoods
} from '@/api/goods'
import ListContent from "@/components/ListContent";

function compare(property) {
  return function (a, b) {
    var value1 = a[property];
    var value2 = b[property];
    return value1 - value2;
  }
}

export default {
  name: "ZDJHQuery",
  components:{
    ListContent
  },
  data() {
    return {
      form: {
        khname: '',
        startTime: '',
        endTime: ''
      },
      result: [],
      result_detail: [],
      totalJe: 0,
      totalQk: 0,
      result_loading: false,
      activeIndex: 0,
      collapse: true,
      intervalId: null,
      goodStorageDialog: false,
      kcInf: null,
    }
  },
  computed: {
    curCust() {
      return this.result.filter((x) => x.dh === this.activeIndex)[0]
    }
  },
  watch: {
    activeIndex() {
      this.collapse = true
      setTimeout(() => {
        this.collapse = false
      }, 500)
    },
    result() {
      this.calc()
    }
  },
  methods: {
    calc(){
      this.totalJe = 0
      this.totalQk = 0
      this.result.forEach(each=>{
        this.totalJe += each.je
        this.totalQk += each.qk
      })
      this.totalJe = this.totalJe.toFixed(2)
      this.totalQk = this.totalQk.toFixed(2)
    },
    searchBill() {
      if (this.form.khname !== '') {
        this.result_loading = true
        queryJH(this.form).then(res => {
          if (res.code === 200) {
            this.result = res.data.zd
            this.result_detail = res.data.zd_detail
            if (res.data.zd.length) {
              let totalJe = 0, totalQk = 0
              res.data.forEach((each) => {
                totalJe += each.je
                totalQk += each.qk
              })
              this.totalJe = totalJe
              this.totalQk = totalQk
            } else {
              this.$message.warning('无数据')
            }
          }
        }).finally(() => {
          this.result_loading = false
          this.currentIndex = null
        })

        this.$buryingPoint('查询进货账单', JSON.stringify(this.form))
      } else {
        getRecentZD().then((res) => {
          this.result = res.data
          this.currentIndex = null
        })

        this.$buryingPoint('查询进货账单-最近', null)
      }
    },
    async clickItem(dh) {
      this.activeIndex = dh
      this.collapse = false
      await this.$nextTick()
      let offsetTop = document.getElementById(`list${dh}`).offsetTop
      console.log(offsetTop)
      window.scrollTo({ left: 0, top: offsetTop + 30, behavior: 'smooth' })
    },
    jumpTodetail(dh) {
      this.$router.push({path: '/zd/detail', query: {dh}})
    },
    async checkKc(spbh) {
      let result = await queryGoods(spbh)
      console.log(result)
      this.kcInf = result.data[0]
      this.goodStorageDialog = true
    },
    collaspeDetail(flag) {
      this.detail_collaspe = flag
    },
    handleChange(val) {
      if (val !== '') {

        this.currentIndex = val

        setTimeout(() => {
          this.jumpToCurrent()
        }, 800)

        this.detail_data = this.result_detail[this.result[val].dh]
        this.detail_collaspe = true

        // this.detail_collaspe = true
        // this.detail_loading = true
        // getJHdetail(this.result[val].dh).then((res) => {
        //   this.detail_data = res.data
        // }).finally(() => {
        //   this.detail_loading = false
        // })
      }
    },
    getThatDayData() {
      let startTime = this.form.startTime
      let data = {
        thatDay: startTime
      }
      this.result_loading = true
      getThatDayJH(data).then((res) => {
        this.result = res.data.zd.sort(compare('dh'))
        this.result_detail = res.data.zd_detail
        this.calc()
      }).finally(() => {
        this.result_loading = false
        this.currentIndex = null
      })

      this.$buryingPoint('查询进货账单-当天', null)
    },
    jumpToCurrent() {
      let currentRoute = this.$route.path
      let a = document.createElement('a')
      a.href = '#' + this.currentIndex
      let body = document.querySelector('body')
      body.appendChild(a)
      a.click()
      body.removeChild(a)
      this.$router.push(currentRoute)
    },
    hasRead(){
      let dh = this.result[this.currentIndex].dh
      this.result[this.currentIndex].isRead = "1"
      hasReadZd(dh, '2').then(res=>{
        console.log(res.msg)
      })

      if(this.currentIndex !== this.result.length - 1){
        let num = this.currentIndex + 1
        this.$refs.jh_collapse.setActiveNames(num)
        setTimeout(()=>{
          this.jumpToCurrent()
        }, 1500)
      }
    },
    handleClose() {
      this.goodStorageDialog = false
    },
    hasQuest(){
      let dh = this.result[this.currentIndex].dh
      this.result[this.currentIndex].isRead = "2"
      hasQuestZd(dh, '2').then(res=>{
        console.log(res.msg)
      })

      if(this.currentIndex !== this.result.length - 1){
        let num = this.currentIndex + 1
        this.$refs.jh_collapse.setActiveNames(num)
        setTimeout(()=>{
          this.jumpToCurrent()
        }, 1500)
      }
    },
    getQuest(){
      this.result_loading = true
      getQuestZD('2').then(res=>{
        this.currentIndex = null
        this.detail_collaspe = false
        this.result = res.data.zd
        this.result_detail = res.data.zd_detail
        this.calc()
        // this.calcTotal()
      }).finally(()=>{
        this.result_loading = false
      })
    }
  },
  created() {
    const date = new Date();
    const date2 = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
    this.form.startTime = date.toLocaleDateString().replace(/\//g, '-')
    this.form.endTime = date2.toLocaleDateString().replace(/\//g, '-')

  },
  mounted() {
    let data = {
      thatDay: this.form.startTime
    }
    this.result_loading = true
    getThatDayJH(data).then((res) => {
      this.result = res.data.zd.sort(compare('dh'))
      this.result_detail = res.data.zd_detail
      this.calc()
      // this.result = res.data
    }).finally(()=>{
      this.result_loading = false
    })

    this.$buryingPoint('查询进货账单-最近', null)

    this.intervalId = setInterval(() => {
      let ele = document.querySelector('#app > div > div.sidebar-container > div > div.scrollbar-wrapper.el-scrollbar__wrap')
      let ele2 = document.querySelector('.detail-collapse')
      if (ele.clientWidth > 200 && document.body.clientWidth < 1000) {
        ele2.setAttribute('style', 'left: 0')
      } else {
        ele2.setAttribute('style', 'left:' + ele.clientWidth + 'px')
      }
    }, 1000)
  },
  destroyed() {
    clearInterval(this.intervalId)
  }
}
</script>

<style lang="scss" scoped>
.main {
  max-width: 600px;
  padding: 10px;

  .filter {
    .el-input {
      margin-bottom: 5px;
    }

    .search-btn {
      width: 100%;
    }

    .el-date-editor {
      margin-right: 10px;
    }
  }
  .sum {
    font-size: 10px;
    color: #999999;
    text-align: center;
    margin-top: 10px;
  }
  .result-dj {
    margin-top: 10px;

    .box {
      width: 100%;
      border: 1px solid #DCDFE6;
      border-radius: 8px;
      margin-bottom: 10px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      padding: 10px;
      transition: height 0.5s ease;

      &.active {
        border: 2px solid #4271ff;
      }

      .custName {
        width: 100%;
        font-size: 12px;
        display: inline-flex;
        justify-content: space-between;
        color: #666666;

        .ml {
          font-weight: bold;
          font-size: 10px;
          margin-right: 10px;
          &.yl {
            color: #67c23a;
          }

          &.kq {
            color: #dd6161;
          }
        }

        .je {
          font-weight: bold;
          font-size: 14px;

          &.qk {
            color: #dd6161;
          }

          &.jj {
            color: #67c23a;
          }
        }
      }

      .hide-content {
        margin-top: 10px;
        padding: 5px 0 0 0;
        border-top: 1px solid #DCDFE6;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;

        .content-item {
          width: 50%;
          font-size: 12px;
          line-height: 18px;
          color: #666666;
        }
      }
    }
  }

  .dj-detail {
    position: fixed;
    max-width: 600px;
    //min-height: 50vh;
    width: 100vw;
    bottom: 0;
    left: 0;
    border-radius: 8px 8px 0 0;
    transition: all 0.5s ease;
    &.collapse {
      bottom: -50vh;
    }

    .dj-title {
      width: 100%;
      height: 30px;
      background-color: #e1dfdf;
      display: inline-flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      border-top: 1px solid #DCDFE6;
      border-bottom: 1px solid #DCDFE6;
      font-size: 12px;
      color: #666666;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-radius: 8px 8px 0 0;

      .total-flex {
        display: inline-flex;
        align-items: center;
      }

      .ml {
        font-weight: bold;
        font-size: 10px;
        margin-right: 10px;
        &.yl {
          color: #67c23a;
        }

        &.kq {
          color: #dd6161;
        }
      }

      .total {
        font-weight: bold;
        margin-right: 10px;

        &.qk {
          color: #dd6161;
        }

        &.jj {
          color: #67c23a;
        }
      }
    }

    .dj-list {
      background-color: #f1f1f1;
      font-size: 12px;
      color: #666666;
      padding-bottom: 40px;
      max-height: 60vh;
      min-height: 40vh;
      overflow: scroll;
      overscroll-behavior: none;

      .dj-list-item {
        padding: 0 10px;
        width: 100%;
        line-height: 18px;
        border-bottom: 1px solid #DCDFE6;
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        .spname {
          width: 45%;
          font-weight: bold;
        }

        .dj {
          width: 45%;
        }

        .sl, .jj {
          width: 30%;
        }

        .xj, .ml {
          width: 25%;
          text-align: right;
        }

        .dj, .jj, .ml {
          background-color: #f1f1f1;
        }

        & > div {
          line-height: 25px;
          height: 25px;
          border-bottom: 1px solid #DCDFE6;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}

.view-line {
  display: inline-flex;
  justify-content: space-between;
  border-bottom: 1px solid #DCDFE6;
  padding: 10px;
  width: 100%;
}

html {
  scroll-behavior: smooth;
}
</style>
